package controllers;

import models.*;
import play.modules.gae.GAE;
import play.mvc.Before;

import java.util.ArrayList;
import java.util.Collection;

public class Games extends Application {

    @Before
    static void checkConnected() {
        if (GAE.getUser() == null) {
            Application.login();
        } else {
            renderArgs.put("user", GAE.getUser().getEmail());
        }
    }

    public static void create(Long id) {
        Deck deck = Deck.findById(id);
        ArrayList<Deck> decks = new ArrayList<Deck>();
        decks.add(deck);
        if (deck.getCards().size() > 0) {
            Game game = Game.createGame(decks);
            game.update();
            flash.success("New game created! \"%s\"", "" + game.name);
            show(game.id);
        } else {
            flash.error("Cannot create game with this deck. The deck contains no cards.");
            Decks.index();
        }
    }

    public static void delete(Long id) {
        Game game = Game.findById(id);
        game.delete();
        flash.success("Game \"" + game.name + "\"deleted");
        Decks.index();
    }

    public static void show(Long id) {
        Game game = Game.findById(id);
        notFoundIfNull(game);
        Collection<Card> cards = game.cards();
        Evaluation currentEvaluation = game.getCurrentEvaluation();
        GameStatistics statistics = game.calcGameStatistics();
        render(game, cards, currentEvaluation, statistics);
    }

    public static void markCurrentAsCorrect(Long gameId) {
        updateUserEvaluation(gameId, Evaluation.UserEvaluation.CORRECT);
    }

    public static void markCurrentAsIncorrect(Long gameId) {
        updateUserEvaluation(gameId, Evaluation.UserEvaluation.INVALID);
    }

    private static void updateUserEvaluation(Long gameId, Evaluation.UserEvaluation userEvaluation) {
        Game game = Game.findById(gameId);
        game.updateUserEvaluation(userEvaluation);
        if (!game.completed) {
            game.setRandomEvaluation();
            show(gameId);
        } else {
            flash.success("Congrats! You have completed the game!");
            Decks.index();
        }
    }


}
